package cn.felord.common.security;

import cn.felord.common.entity.dto.ResourceRole;
import cn.felord.common.security.event.UrlRolesRefreshEvent;
import cn.felord.common.service.ISysResourcesService;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationListener;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 自定义 url 权限元数据.
 *
 * @author Dax
 * @since 20 :55  2018/9/15
 */
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource, ApplicationListener<UrlRolesRefreshEvent>, InitializingBean {
    private static final Logger log = LoggerFactory.getLogger(CustomFilterInvocationSecurityMetadataSource.class);
    private ISysResourcesService iSysResourcesService;
    private List<ResourceRole> resourceRoles;

    /**
     * Instantiates a new Custom filter invocation security metadata source.
     *
     * @param iSysResourcesService the sys resources service
     */
    public CustomFilterInvocationSecurityMetadataSource(ISysResourcesService iSysResourcesService) {
        this.iSysResourcesService = iSysResourcesService;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
//        避免触发刷新事件后 逻辑异常
        List<ResourceRole> temp = resourceRoles;
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
//        所有资源为空放行
        if (CollectionUtil.isEmpty(temp)) {
            return null;
        }

        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
        for (ResourceRole resourceRole : temp) {
            String antPath = resourceRole.getAntPath();
//            资源匹配到ant
            if (antPathMatcher.match(antPath, requestURI)) {
                Set<String> roles = resourceRole.getRoles();
                if (CollectionUtil.isNotEmpty(roles)) {

                    return SecurityConfig.createList(ArrayUtil.toArray(roles, String.class));
                }
            }
        }
        return SecurityConfig.createList(CustomCodeEnum.UN_ROLE.name());

    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(iSysResourcesService, "resources service must not  be  null");
        this.resourceRoles = iSysResourcesService.initUrlRoleStorage();
    }


    @Override
    public void onApplicationEvent(UrlRolesRefreshEvent event) {
        if (event.isSignal()){
            this.resourceRoles = Optional.ofNullable(iSysResourcesService.initUrlRoleStorage()).orElse(Collections.emptyList());
            log.info("urlRoles has been refreshed");
        }
    }
}
